﻿using System;
using System.Collections.Generic;
using System.Web;
using Golos.Web.Utils;
using Golos.Web.handlers;

namespace Golos.Web
{
    /// <summary>
    /// Summary description for Handler
    /// </summary>
    public class Handler : IHttpHandler
    {
        private static readonly Dictionary<string, Type> Handlers = new Dictionary<string, Type>
        {
            {"login", typeof (LoginHandler)},
            {"attachuser", typeof (AttachUserHandler)},
            {"vote", typeof (VoteHandler)},
            {"test", typeof (TestHandler)},
            {"getmypolls", typeof (GetMyPollsHandler)},
            {"getmyvotes", typeof (GetMyVotesHandler)},
            {"getpolls", typeof (GetPollsHandler)},
            {"getpoll", typeof (GetPollHandler)},
            {"addpoll", typeof (AddPollHandler)},
            {"delpoll", typeof (DelPollHandler)},
            {"search", typeof (SearchHandler)},
            {"gettags", typeof (GetTagsHandler)},
            {"getbytag", typeof (GetByTagHandler)}
        };

        public void ProcessRequest(HttpContext httpContext)
        {
            HandleRequest(httpContext);
        }

        public void HandleRequest(HttpContext httpContext)
        {
            string action = httpContext.Request.QueryString["operation"].ToLowerInvariant();
            
            if (Handlers.ContainsKey(action))
            {
                Token token = TokenUtils.FromCookies(httpContext.Request.Cookies);
                if (token != null)
                {
                    LogClass.WriteDebugEntry("User: " + token.User + " start handler " + action);
                    
                    ((IHandler)Activator.CreateInstance(Handlers[action], new[] { httpContext })).Handle();

                    LogClass.WriteDebugEntry("User: " + TokenUtils.FromCookies(httpContext.Request.Cookies).User + " end handler " + action);
                }
                else
                {
                    ((IHandler)Activator.CreateInstance(Handlers[action], new[] { httpContext })).Handle();
                }
            }
            else
                new EmptyHandler(httpContext).Handle();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}